package search;

import java.util.ArrayList;

/**
 * 二分查找
 */
public class BinarySearch {
    public static void main(String[] args) {
        /*int[] arr = {1, 8, 10, 89, 1000, 1234};
        int index = binarySearch(arr, 0, arr.length - 1, 89);
        System.out.println(index);*/

        int[] arr = {1, 8, 10, 89, 1000, 1000, 1000, 1234};
        ArrayList<Integer> integers = binarySearch2(arr, 0, arr.length - 1, 1000);
        System.out.println(integers);
    }

    /**
     * 二分查找
     *
     * @param arr   要查找的数组
     * @param left  范围起始位置
     * @param right 范围终止位置
     * @param value 要查找的值
     * @return 查找到返回索引，没找到返回-1
     */
    public static int binarySearch(int[] arr, int left, int right, int value) {
        if (left > right) {
            //说明没找到
            return -1;
        }

        //找到中间值的位置和中间值
        int mid = left + (right - left) / 2;
        int midValue = arr[mid];
        if (value > midValue) {
            //说明在中间值右边
            return binarySearch(arr, mid + 1, right, value);
        } else if (value < midValue) {
            //说明在中间值左边
            return binarySearch(arr, left, mid - 1, value);
        } else {
            //说明找到了
            return mid;
        }
    }


    /**
     * 查找所有值等于给定值的元素的索引
     *
     * @param arr
     * @param left
     * @param right
     * @param value
     * @return
     */
    public static ArrayList<Integer> binarySearch2(int[] arr, int left, int right, int value) {
        if (left > right) {
            return new ArrayList<Integer>();
        }
        int mid = left + (right - left) / 2;
        int midValue = arr[mid];
        if (value > midValue) {
            return binarySearch2(arr, mid + 1, right, value);
        } else if (value < midValue) {
            return binarySearch2(arr, left, mid - 1, value);
        } else {
            int temp = mid - 1;
            ArrayList<Integer> resIndexList = new ArrayList<>();
            while (temp >= 0 && arr[temp] == value) {
                resIndexList.add(temp);
                temp--;
            }
            resIndexList.add(mid);
            temp = mid + 1;
            while (temp <= right && arr[temp] == value) {
                resIndexList.add(temp);
                temp++;
            }
            return resIndexList;
        }
    }
}
